// src/composables/useHttp.ts
import { ref } from 'vue'
import axios, {AxiosError} from 'axios'

// 创建自定义 Axios 实例（更好控制）
const http = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
        'tenant': 'dushi'
    }
})

// 添加请求拦截器（可添加认证Token等）
http.interceptors.request.use(config => {
    const token = "eyJhbGciOiJIUzUxMiJ9.eyJ0ZW5hbnQiOiJkdXNoaSIsImxvZ2luX3VzZXJfa2V5IjoiN2Q2YWQzNGYtZjBiYS00YzcyLThiNzQtOWE3YWFhNDBkNDgxIn0.gxGwWb1n4p_OA0CWPI0gnlFoWV3YfqFFsMZotzp1NMiDfyd3KSsug-cmGzWM03LYjbRs108QV5FVRtYmumVSow"
    config.headers.Authorization = `Bearer ${token}`
    return config
})

// 状态管理组合式函数
export function useHttp() {
    const data = ref(null)
    const loading = ref(false)
    const error = ref<Error | AxiosError  | null>(null)

    // 核心请求方法
    const execute = async (method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string, payload?: any) => {
        loading.value = true
        error.value = null

        try {
            const response = await http({
                method,
                url,
                data: payload
            })
            data.value = response.data
            return response.data
        } catch (err) {
            error.value = err as AxiosError<{ message?: string }> | Error;
            throw err
        } finally {
            loading.value = false
        }
    }

    return {
        data,
        loading,
        error,
        execute,
        // 快捷方法
        get: (url: string) => execute('GET', url),
        post: (url: string, payload: any) => execute('POST', url, payload),
        put: (url: string, payload: any) => execute('PUT', url, payload),
        del: (url: string) => execute('DELETE', url)
    }
}
